<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 荣誉记录编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />
          <custom-form
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
            @getOption="getOption"
            @onSelectChange="onSelectChange"
          >
            <!-- 附件上传 -->
            <template #fileInfoVOS>
              <template v-if="editModel != 0">
                <l-table
                  business-code="OF02"
                  :upload-arrys.sync="form.fileInfoVOS"
                />
                <div class="file_prompt">
                  支持扩展名：.rar .zip .doc .docx .pdf .jpg...
                </div>
              </template>
              <file-link
                v-else
                :file-list="form.fileInfoVOS"
                style="margin-top: -3px"
              />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          v-if="editModel != 0"
          :loading="loading"
          type="primary"
          class="button_right"
          @click="handleSubmit"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        >
          关闭
        </a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { honorRecord } from '@/api/union/workersCongress' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import Selector from '@/components/Select/Selector'
import SelectOrgPeople from '@/components/Select/SelectOrgPeople' // 班主

export default {
    name:'a'+Date.now(),
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // 加载控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {}, // 表单
      rules: {
        honorName: [{ required: true, whitespace: true, message: '请输入荣誉名称', trigger: 'change' }],
        levelId: [{ required: true, message: '请选择荣誉级别', trigger: 'change' }],
        awardWinningTime: [{ required: true, message: '请选择获奖时间', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择获奖性质', trigger: 'change' }],
        unitId: [{ required: true, message: '请选择获奖单位', trigger: 'change' }],
        employeeId: [{ required: true, message: '请选择获奖人员', trigger: 'change' }],
        awardUnit: [{ required: true, message: '请输入颁发单位 ', trigger: 'change' }],
        // commendationNumber: [{ required: true, whitespace: true, message: '请输入表彰文号', trigger: 'change' }],
        // content: [{ required: true, whitespace: true, message: '请输入主要内容', trigger: 'change' }],
        fileInfoVOS: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }],
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '', // 形式选中项code
      subjectCode: '', // 获奖主体选中项code
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoVOS'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoVOS')
        })
      }
    },
    // 监听形式
    'form.formId'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          if (this.form.otherForm) {
            this.form.otherForm = ''
          } else {
            this.$set(this.form, 'otherForm', '')
          }
        })
      }
    },
    // 监听获奖主体
    'form.typeId'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          if (this.form.unitId) {
            this.form.unitId = this.subjectCode == 0 ? [] : void 0
            this.form.unitName = ''
          } else {
            this.$set(this.form, 'unitId', this.subjectCode == 0 ? [] : void 0)
            this.$set(this.form, 'unitName', '')
          }
        })
      }
    },
  },
  mounted() {
    this.$route.meta.title = ['荣誉记录查看', '荣誉记录编辑', '荣誉记录新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      honorRecord
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading = false
          this.subjectCode = res.data.typeCode
          if (this.editModel == 1) {
            if (this.subjectCode == 1) {
              // 格式化集体信息
              let unitId = res.data.unitId.split(',')
              let unitName = res.data.unitName.split(',')
              res.data.unitId = unitId.map((item, index) => {
                return {
                  key: item,
                  label: unitName[index],
                }
              })
            }
          }
          this.form = res.data
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'typeId',
          viewName: 'typeName',
          label: '获奖性质',
          type: Selector,
          attrs: {
            selectType: '5',
            urlType: 'union',
          },
        },
        {
          keyName: 'employeeId',
          viewName: 'name',
          hidden: this.subjectCode !== '0',
          label: '姓名',
          placeholder: '请选择人员',
          type: SelectOrgPeople,
          attrs: {
            init: true,
            customRender(i) {
              return `${i.name}-${i.phoneNum}`
            },
          },
        },
        {
          keyName: 'unitId',
          hidden: this.subjectCode !== '1',
          viewName: 'unitName',
          placeholder: '请选择获奖单位',
          type: TreeSelectOrganization,
          label: '获奖单位',
          attrs: {
            labelInValue: true,
            orgQuery: {
              containTags: ['CO', 'BC', 'PD'],
              resultWithCODept: true,
              resultWithBCDept: true,
              resultWithPDDept: true,
            },
            containVirtual: true,
          },
        },
        {
          keyName: 'jobTitleName',
          type: 'BaseInput',
          placeholder: '请先选择人员',
          hidden: this.subjectCode !== '0',
          disabled: true,
          span: 24,
          label: '工作职务',
        },
        {
          keyName: 'unitName',
          type: 'BaseInput',
          placeholder: '请先选择人员',
          hidden: this.subjectCode !== '0',
          disabled: true,
          span: 24,
          label: '单位',
        },
        {
          keyName: 'honorName',
          type: 'BaseInput',
          label: '荣誉名称',
        },
        {
          keyName: 'levelId',
          viewName: 'levelName',
          label: '荣誉级别',
          type: Selector,
          attrs: {
            selectType: '6',
            urlType: 'union',
          },
        },
        {
          keyName: 'awardUnit',
          type: 'BaseInput',
          label: '颁发单位',
        },
        {
          keyName: 'awardWinningTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '获奖时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
        {
          keyName: 'commendationNumber',
          type: 'BaseInput',
          label: '表彰文号',
        },
        {
          keyName: 'content',
          type: 'BaseTextarea',
          label: '备注',
          span: 24,
        },
        {
          slot: true,
          keyName: 'fileInfoVOS',
          label: '附件',
          span: 24,
        },
      ]
    },
  },
  methods: {
    /**
     * 选择人员更新工作职务和单位
     */
    onSelectChange() {
      // console.log(arguments)
      let jobTitleName = arguments[1].postPNames
        ?.map((item) => {
          let index = item.split('/').length - 1
          return item.split('/')[index]
        })
        ?.join('/')
      let unitName = arguments[1].postPNames?.map((item) => item.split('/')[0])?.join('/')
      this.form.employeeId = arguments[1].userId
      this.form.name = arguments[1].name
      if (jobTitleName) {
        this.$set(this.form, 'jobTitleName', jobTitleName)
      }
      if (unitName) {
        this.$set(this.form, 'unitName', unitName)
      }
    },
    /**
     * 获取选中项code
     */
    getOption(name, e) {
      if (e) {
        // 获取形式code
        if (name === 'typeId') {
          this.subjectCode = e.code
        }
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      let api = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 提交表单
          that.loading = true
          let form = that.$clone(that.form)
          if (this.subjectCode == 1) {
            form.unitName = form.unitId.label
            form.unitId = form.unitId.value
          } else {
            delete form.unitId
          }
          // 格式化文件列表
          if (form.fileInfoVOS.length > 0) {
            form.fileId = form.fileInfoVOS.map((item) => item.commonId).join()
          }
          honorRecord[api](form)
            .then(() => {
              that.loading = false
              that.$message.success('提交成功！')
              that.$multiTab.close()
            })
            .catch(() => {
              that.loading = false
            })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>
